var domain = document.location.hostname;
domain = getsubdomain(domain,3);
domain = domain ? "domain=." + domain : "";

// 获取cookie
function getCookieBylogin(name){
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') c = c.substring(1, c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
  }
}
// 切换门户页面登录状态
function loginStatusSwitch(){
  var cookieValue = getCookieBylogin('cisCode');
  var loginButton = document.getElementById('loginDiv');
  var signOutButton = document.getElementById('logoutDiv');
  if(!loginButton || !signOutButton) return;
  if (cookieValue) {
    loginButton.style.display = 'none';
    signOutButton.style.display = 'block';
  } else {
    loginButton.style.display = 'block';
    signOutButton.style.display = 'none';
  }
}
// 获取n级域名
function getsubdomain(domain,level){
  try{
      var subdomain = "";
      const domainList = domain.split('.');
      const ipAddressReg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
      // 如果为ip或localhost，则直接返回
      if(ipAddressReg.test(domain) || domain === 'localhost'){
          return domain;
      }
      var subdomainItems = [];
      while(domainList.length && level > 0){
          subdomainItems.unshift(domainList.pop());
          level--;
      }
      subdomain = subdomainItems.join(".");
      return subdomain;
  }catch(e){
      return domain;
  }
}
// 登出：删除cookie
function onClickSignout(){
  document.cookie = 'cisCode=;'+domain+';expires= Thu, 01 Jan 1970 00:00:00 UTC;path=/';
  document.cookie = 'groupList=;'+domain+';expires= Thu, 01 Jan 1970 00:00:00 UTC;path=/';
  loginStatusSwitch();
  location.reload();
}
// 将用户身份写入cookie中（有效期为30分钟）
function setCisInfoToCookie(cisNo,groupList){
  var exdate = new Date();
  exdate.setTime(exdate.getTime() + 30 * 60 * 1000);
  if(cisNo && cisNo !== 'undefined'){
    document.cookie = "cisCode=" + cisNo +";"+ domain + ";expires=" + exdate.toUTCString() + ";path=/";
    if (groupList && groupList.length != 0) {
      document.cookie = "groupList=" + JSON.stringify(groupList) +";"+ domain + ";expires=" + exdate.toUTCString() + ";path=/";
    }
  }
}
// 定义节流函数:防止频繁触发，1分钟执行一次写入操作 
function throttleSetCookie(func, delay) {
  // 记录最后一次被调用时间（闭包：数据私有化，无法修改lastCall的值，只能通过内部function修改）
  let lastCall = null;
  return function() {
    let cisNo = getCookieBylogin('cisCode') || '';
    let groupList = getCookieBylogin('groupList') || '[]';
    groupList = JSON.parse(groupList);
    if(!cisNo || cisNo === 'undefined'){
      document.removeEventListener('mousemove', mousemoveFun);
      document.removeEventListener('mousedown', mousedownFun);
      document.removeEventListener('keydown', keydownFun);
      location.reload();
      return ;
    }
    if (!lastCall || Date.now() - lastCall >= delay) {
      lastCall = Date.now();
      func.apply(this, [cisNo,groupList]);
    }
  };
}

var mousemoveFun = null;
var mousedownFun = null;
var keydownFun = null;
// 监听用户行为：：鼠标移动、鼠标点击、键盘输入，更新cookie有效时间
function addEventForUser(delay){
  document.addEventListener('mousemove', mousemoveFun = throttleSetCookie(setCisInfoToCookie, delay));
  document.addEventListener('mousedown', mousedownFun = throttleSetCookie(setCisInfoToCookie, delay));
  document.addEventListener('keydown', keydownFun = throttleSetCookie(setCisInfoToCookie, delay));
}

// 用户身份带入
function loginByMyBank() {
  // 1. 获取当前页面url
  var currentUrl = window.location.href;
  // 2. 通过url中的参数获取客户信息（加密前的）
  var params = currentUrl.indexOf('?') >= 0 ? currentUrl.split('?')[1].split('&') : [];  
  if(params.length == 0) {
    if(getCookieBylogin('cisCode')){
      addEventForUser(60 * 1000);
      return;
    }
    return;
  }
  var encTranData = "";
  var merSignMsg = "";
  for(var i = 0; i < params.length; i++){
    var param= params[i].trim(); 
    // 加密串
    if(param.indexOf('encTranData')===0){
      encTranData = param.split('=')[1];
    }
    // 签名串
    if(param.indexOf('merSignMsg')===0){
      merSignMsg = param.split('=')[1];
    }
  }
  // 3. 后台发送ajax请求进行解密，从而获取客编和手机号
  var urlEbankp = "//" + window.appConfig.papi.host + "/icbc/iepa/portalinfo/user/decryption/ebankp";
  var paramsEbankp = {
    encTranDataString: encTranData,
    merSignMsgString: merSignMsg
  }
  $.ajax({
    url: urlEbankp,
    data: JSON.stringify(paramsEbankp),
    type: "POST",
    contentType: 'application/json',
    success: function (res) {
      if (res.code === 0) {
        var cisInfo = res.data;
        var cisNo = (typeof cisInfo == "object" && cisInfo.cisCode) || "";
        if((cisNo == "" && getCookieBylogin('cisCode')) ||(cisNo != "" && getCookieBylogin('cisCode') === cisNo)) {
          addEventForUser(60 * 1000);
          return;
        }
        var phoneList = (typeof cisInfo == "object" && cisInfo.phoneList) || [];
        if(cisNo != "" || phoneList.length != 0){
          // 4. 后台发送ajax请求，获取客群编号
          var urlGroupList = "//" + window.appConfig.papi.host + "/icbc/iepa/portalinfo/user/getGroupListByCondition";
          var paramsGroupList = {
              cisNo: cisNo,
              phoneList: phoneList,
          }
          var groupList = []
          $.ajax({
            url: urlGroupList,
            data: JSON.stringify(paramsGroupList),
            type: "POST",
            contentType: 'application/json',
            success: function (res) {
              if (res.code === 0) {
                for(var i = 0; i<res.data.length; i++){
                    groupList.push(res.data[i]["groupId"])
                }
              }
              // 5. 将客编和客群编号存入cookie 并 监听用户操作
              setCisInfoToCookie(cisNo,groupList);
              addEventForUser(60 * 1000);
              // 6. 更新登录状态 并 刷新页面
              loginStatusSwitch();
              location.reload();
            },
            error: function (err) {
              setCisInfoToCookie(cisNo,groupList);
              addEventForUser(60 * 1000);
              loginStatusSwitch();
              location.reload();
            }
          });  
        }
      }
    }
  });   
}
